#pragma once
#include <event2/event.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/listener.h>
#include <event2/util.h>
#include <memory>
#include <map>
#include <queue>
#include "message_buffer.h"
#include "timer.h"
#include "json_packet.h"

class MessageBuffer;

//网络基础会话类
class NetworkSessionBase
{
public:
	NetworkSessionBase(struct event_base* event_base)
		:_event_base(event_base)
		, _per_destroy(false)
		, _fd(-1)
		, _heartbeat(true)
		, _is_destroy(false)
	{}
	bool InitAccept(int fd);
	virtual void Send(const std::string& str);
	virtual void Send(const char* data, size_t length);
	void Destroy();
	void Free();
protected:
	void SendBase(const char* data, size_t length);
	static void conn_readcb(struct bufferevent *bev, void *user_data);
	static void conn_eventcb(struct bufferevent *bev, short events, void *user_data);
	static void conn_writecb(struct bufferevent *bev, void *user_data);
	virtual int HandleMessage();
	virtual int BeforeDestroy() {};
protected:
	struct event_base* _event_base;
	struct bufferevent *_bev;
	std::queue<MessageBuffer> _wbufs;
	MessageBuffer _rbuf;
	bool _per_destroy;
public:
	bool _is_destroy;
	int _fd;
	bool _heartbeat;
	JsonPacket _jpacket;
};

//网络基类
class NetworkBase : public AsyncTimer
{
public:
	NetworkBase(struct event_base* event_base);
	bool InitListen(short port);
protected:
	virtual NetworkSessionBase* NewSession(int fd);
	static void listener_cb(struct evconnlistener *listener, evutil_socket_t fd,
		struct sockaddr *sa, int socklen, void *user_data);
	bool DelSession(NetworkSessionBase* base);
public:
	NetworkSessionBase * operator[](int fd);
protected:
	struct event_base* _event_base;
	struct evconnlistener *_listener;
	GameTimer	_heartbeat_timer;
public:
	static std::map<int, NetworkSessionBase*> _sessions_dict;//连接索引
	std::vector<NetworkSessionBase*> _sessions;//所有连接
};